<template>
  <div class="fit row no-wrap justify-between items-start">
    <qx-tree v-if="!isXS" :loading="loading" :options="orgTree" :props="props"
             classes="q-col-125rem bg-white shadow-1 full-height" @change="treeChange"></qx-tree>
    <qx-table :option="formOption" :remoteData="remoteData" class="col q-ml-md">
      <template v-if="isXS" v-slot:top>
        <qx-form v-model="searchForm" :option="searchOption" isSearch @submit="startSearch"></qx-form>
      </template>
      <template v-slot:menuLeft="{ selected }">
        <q-btn v-auth="['memberPost:save']" color="primary" icon="add" unelevated @click="handleCreate">
          {{ $t('Add') }}
        </q-btn>
        <q-btn v-auth="['memberPost:update']" :disable="isDisable(selected)" icon="mdi-square-edit-outline" outline
               text-color="primary" @click="handleUpdate(selected[0])">
          {{ $t('Edit') }}
        </q-btn>
        <q-btn v-auth="['memberPost:delete']" :disable="isDisable(selected)" icon="delete" outline text-color="primary"
               @click="handleDelete(selected[0])">
          {{ $t('Del') }}
        </q-btn>
      </template>
    </qx-table>
  </div>
  <q-modal v-model="modalVisible" :header="formInfo.id ? $t('Edit') : $t('Add')" :width="500" btnAlign="center"
           position="right" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="PostCfg" v-model="formInfo" :option="formOption"></qx-form>
  </q-modal>
</template>

<script setup>
import { useQuasar } from 'quasar'
import { deleteAPI, postAPI, putAPI } from 'src/api'
import { i18n, toI18nName } from 'boot/i18n'
import { yesOrNo } from 'src/enum'
import { createDialog, deepClone } from 'src/utils/utils'
import { computed, onMounted, reactive, ref } from 'vue'

const $q = useQuasar()
const orgTree = ref([])
const formInfo = ref({})
const postList = ref([])
const PostCfg = ref(null)
const loading = ref(false)
const searchForm = ref({})
const postTypeList = ref([])
const modalVisible = ref(false)
const props = reactive({ label: toI18nName('orgNameZhCn'), children: 'childs' })
const isXS = computed(() => $q.screen.width < 850)
const isDisable = computed(() => selected => !selected || selected.length !== 1 || selected[0].sysInner === '1')
const searchOption = computed(() => {
  return {
    labelWidth: 70, searchSpan: 12, searchMenu: 12, searchMenuPosition: 'center',
    column: [{
      label: `${i18n.t('SystemCore.SubjectionOrg')}`, field: 'orgId', type: 'tree', options: orgTree.value,
      props, display: isXS.value
    }]
  }
})
const formOption = computed(() => {
  return {
    labelWidth: 100, searchLabelWidth: 70, selection: 'single', menuBtn: false, span: 22,
    column: [{
      label: `${i18n.t('SystemCore.SubjectionOrg')}`, field: 'orgId', type: 'tree', options: orgTree.value,
      props, search: false, required: true, change: val => getPost(val),
      format: (_, row) => row[toI18nName('orgNameZhCn')], minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.SuperiorPosition')}`, field: 'parentId', type: 'select', options: postList.value,
      props: { label: toI18nName('postNameZhCn'), value: 'id' }, search: false, required: true,
      format: (val, row) => {
        if (val === '-1') return i18n.t('Nothing')
        return row[toI18nName('parentPostNameZhCn')]
      }, minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.PositionType')}`, field: 'postType', type: 'select', options: postTypeList.value,
      props: { label: toI18nName('dictNameZhCn'), value: 'dictKey' }, required: true, minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.PositionCode')}`, field: 'code', required: true, minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.PositionNameENUS')}`, field: 'postNameEnUs', hide: true, minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.PositionName')}`, field: 'postNameZhCn', required: true, minWidth: 80
    }, {
      label: `${i18n.t('BuiltIn')}`, field: 'sysInner', search: false, display: false, align: 'center',
      options: yesOrNo.value, useTag: true, minWidth: 80
    }, {
      label: `${i18n.t('Remarks')}`, field: 'remark', type: 'textarea', search: false, minWidth: 120, maxlength: 200
    }]
  }
})

const getOrgTree = () => {
  loading.value = true
  postAPI('/member/api/memberOrg/listTree', {}, data => {
    orgTree.value = data
    loading.value = false
  }, () => (loading.value = false))
  const params = {
    pageSize: '-1',
    andDynamicQueryItems: [{ property: 'dictTypeCode', value: 'SYS_Post_TYPE', criterion: 'andEqualTo' }],
    orderByItems: [{ property: 'sortId', orderType: 'ASC' }]
  }
  postAPI('/config/api/cfgDictData/list', params, data => {
    postTypeList.value = data.rows
  })
}
getOrgTree()

const handleCreate = () => {
  formInfo.value = {}
  modalVisible.value = true
}

const getPost = value => {
  if (!value) {
    postList.value = []
    formInfo.value.postId = ''
    return
  }
  const params = { pageSize: '-1' }
  params.andDynamicQueryItems = [{ criterion: 'andEqualTo', property: 'orgId', value }]
  postAPI('/member/api/memberPost/list', params, data => {
    postList.value = [{ postNameZhCn: '无', postNameEnUs: 'Nothing', id: '-1' }, ...data.rows]
    const index = postList.value.findIndex(el => el.id === formInfo.value.parentId)
    if (index === -1) formInfo.value.postId = ''
  }, () => (postList.value = []))
}

const handleUpdate = row => {
  formInfo.value = deepClone(row)
  modalVisible.value = true
}

const formatSearchForm = () => {
  const params = { ...searchForm.value }
  params.andDynamicQueryItems = []
  if (params.nickName) {
    params.andKeywordLikeItem = [{
      keyword: params.nickName, propertys: ['nickName']
    }]
    delete params.nickName
  }
  if (params.orgId) {
    params.andDynamicQueryItems.push({ criterion: 'andEqualTo', property: 'orgId', value: params.orgId })
    delete params.orgId
  }
  return params
}

const remoteData = ref({ dicUrl: '/member/api/memberPost/list' })
onMounted(() => startSearch())

const handleDelete = row => {
  createDialog({ msg: `${i18n.t('DelTips')}` }, () => {
    deleteAPI(`/member/api/memberPost/${row.id}`, {}, () => startSearch())
  }, () => {})
}

const treeChange = target => {
  searchForm.value.orgId = target
  remoteData.value.params = formatSearchForm()
}

const beforeClose = () => {
  if (PostCfg.value) PostCfg.value.onReset()
  modalVisible.value = false
}

const startSearch = (_, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
}

const submitForm = (mDone) => {
  PostCfg.value.validate((form, done) => {
    const API = form.id ? putAPI : postAPI
    API('/member/api/memberPost', form, () => {
      startSearch()
      done()
      if (mDone) mDone()
    }, () => {
      done()
      if (mDone) mDone(false)
    })
  }, () => {
    if (mDone) mDone(false)
  })
}

</script>